#include "framelesswindow.h"
#include "ui_framelesswindow.h"

#include "widgets/picimage/picimage.h"

#include <QLabel>
#include <QtConcurrent>
#include <httpclient.h>
#include <screenutil.h>

#include <widgets/iconmanager.h>

FramelessWindow::FramelessWindow(QWidget *parent) :
    FramelessWidget(parent),
    ui(new Ui::FramelessWindow)
{
    ui->setupUi(this);
    setWindowTitle("Linglong Apps");

    setupUi(ui->frame);
    setTitleLayout(ui->horizontalLayout);
    setTitleIcon(QPixmap("://icon.svg").scaled(35,35, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    initUI();

    load_linglong_metadata();
}

FramelessWindow::~FramelessWindow()
{
    delete ui;
    manager->stop();
    manager->deleteLater();
}

void FramelessWindow::initUI()
{
//    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    //    ui->tableWidget->verticalHeader()->hide();
    //    connect(ui->tableWidget, &QTableWidget::itemDoubleClicked, this, &RecordSelectorDialog::slotItemDoubleClicked);
}

void FramelessWindow::load_linglong_metadata()
{
    QtConcurrent::run([this](){
        auto url = "https://mirror-repo-linglong.deepin.com/api/v0/web-store/apps??page=1&size=10000";
        auto list = HttpClient::instance().get(url).toMap().value("data").toMap().value("list").toList();
        qDebug() << list.count();
        qDebug() << "id:"          << list.at(0).toMap().value("id").toInt();
        qDebug() << "appId:"       << list.at(0).toMap().value("appId").toString();
        qDebug() << "name:"        << list.at(0).toMap().value("name").toString();
        qDebug() << "version:"     << list.at(0).toMap().value("version").toString();
        qDebug() << "arch:"        << list.at(0).toMap().value("arch").toString();
        qDebug() << "icon:"        << list.at(0).toMap().value("icon").toString();
        qDebug() << "description:" << list.at(0).toMap().value("description").toString();

        QMetaObject::invokeMethod(this, "slot_linglong_metadata", Qt::QueuedConnection, Q_ARG(const QVariantList &, list));
    });
}

void FramelessWindow::slot_linglong_metadata(const QVariantList &list)
{
    /**
    data.list
    {
        "id": 291,
        "appId": "app.web.baidu.map",
        "name": "baidumap",
        "version": "0.9.1",
        "arch": "arm64",
        "icon": "https://mirror-repo-linglong.deepin.com/icon/app.web.baidu.map.svg",
        "description": "百度地图网页版。"
    },
     */
    auto headers = QStringList() << "id" << "appId" << "name" << "version" << "arch" << "icon" << "description";
    ui->tableWidget->setColumnCount(headers.count());
    ui->tableWidget->setHorizontalHeaderLabels(headers);
    ui->tableWidget->setRowCount(list.count());

    // label.setPixmap(QPixmap::fromImage(QImage::fromData(HttpClient::instance().get(list.at(0).toMap().value("icon").toString()).content())));
    // label.show();

    for (int i = 0; i < list.count(); ++i) {
        auto v = list.at(i);
        auto item_id = new QTableWidgetItem();
        item_id->setText(QString::number(v.toMap().value("id").toInt()));
        auto item_appId = new QTableWidgetItem();
        item_appId->setText(v.toMap().value("appId").toString());
        auto item_name = new QTableWidgetItem();
        item_name->setText(v.toMap().value("name").toString());
        auto item_version = new QTableWidgetItem();
        item_version->setText(v.toMap().value("version").toString());
        auto item_arch = new QTableWidgetItem();
        item_arch->setText(v.toMap().value("arch").toString());

        auto item_icon = new PicImage();
        item_icon->setObjectName(v.toMap().value("appId").toString());

        auto item_description = new QTableWidgetItem();
        item_description->setText(v.toMap().value("description").toString());

        ui->tableWidget->setItem(i, 0, item_id);
        ui->tableWidget->setItem(i, 1, item_appId);
        ui->tableWidget->setItem(i, 2, item_name);
        ui->tableWidget->setItem(i, 3, item_version);
        ui->tableWidget->setItem(i, 4, item_arch);
        ui->tableWidget->setCellWidget(i, 5, item_icon);
        ui->tableWidget->setItem(i, 6, item_description);

    }

    HttpClient::instance().setAutoLocation(true);

    manager = new IconManager(this);
    manager->start();
    manager->setDpr(ScreenUtil::ratio(this));
    connect(manager, &IconManager::onRequested, this, &FramelessWindow::slotIconRequested, Qt::DirectConnection);

    emit manager->onRequestJson(QJsonDocument::fromVariant(list).toJson());
}

void FramelessWindow::slotIconRequested(QPixmap pixmap, QString objectName)
{
    PicImage *item_icon = ui->tableWidget->findChild<PicImage*>(objectName);
    item_icon->setAllowMouseLeftClick(false);
    if (item_icon) {
        item_icon->setImage(pixmap);
    }
}

void FramelessWindow::on_lineEdit_textChanged(const QString &arg1)
{
    if (arg1.isEmpty()) {
        for (int var = 0; var < ui->tableWidget->rowCount(); ++var) {
            ui->tableWidget->showRow(var);
        }
        return;
    }

    for (int var = 0; var < ui->tableWidget->rowCount(); ++var) {
        ui->tableWidget->hideRow(var);
    }

    foreach (auto var, ui->tableWidget->findItems(arg1, Qt::MatchFlag::MatchContains)) {
        ui->tableWidget->showRow(var->row());
    }
}

